<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <div class="filter-container">
      <el-input
        @keyup.enter.native="handleFilter"
        style="width: 200px"
        class="filter-item"
        placeholder="小说名称"
        v-model="keyword"
      >
      </el-input>

      <!-- <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.type" placeholder="类型">
        <el-option v-for="item in  typeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key">
        </el-option>
      </el-select> -->

      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="search"
        @click="handleFilter"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        @click="handleCreate"
        icon="edit"
        >添加</el-button
      >

      <el-button
        class="filter-item"
        type="primary"
        @click="handleDelAll"
        icon="edit"
        >批量删除</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="document"
        @click="handleDownload"
        >导出</el-button
      >
    </div>

    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="novels"
      border
      fit
      highlight-current-row
      :cell-style="{ fontSize: '12px' }"
    >
      <el-table-column type="selection" width="40"> </el-table-column>

      <el-table-column align="center" label="序号" width="65">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="封面" width="100">
        <template slot-scope="scope">
          <el-image fit="contain" :src="scope.row.cover"></el-image>
        </template>
      </el-table-column>

      <el-table-column label="小说名称" align="center" width="180">
        <template slot-scope="scope">
          <router-link
            :to="`rollsManage/rollList?novel_id=${scope.row.novel_id}`"
            >{{ scope.row.novel_title }}</router-link
          >
        </template>
      </el-table-column>

      <el-table-column label="类别" align="center" width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.type_title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="作者" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.novel_author }}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="created_at"
        label="简介"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.novel_intro.trim() | simpleIntro }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="标签" width="130">
        <template slot-scope="scope">
          <!-- <i class="el-icon-time"></i> -->
          <span>{{ scope.row.novel_tag }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="120">
        <template slot-scope="scope">
          {{ scope.row.novel_state }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">
          <el-row
            type="flex"
            style="margin-bottom: 5px"
            justify="center"
            class="row-bg"
          >
            <el-button size="small" @click="handleShow(scope.row)"
              >查看海报</el-button
            >
          </el-row>
          <el-row
            type="flex"
            class="row-bg"
            style="margin-bottom: 5px"
            justify="center"
          >
            <el-button size="small" @click="handleSet(scope.row)"
              >设置海报</el-button
            >
          </el-row>
          <el-row
            type="flex"
            class="row-bg"
            style="margin-bottom: 5px"
            justify="center"
          >
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
          </el-row>
          <el-row
            type="flex"
            class="row-bg"
            style="margin-bottom: 5px"
            justify="center"
          >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.currPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="查看海报"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeBanner"
    >
      <el-form ref="bannerForm" :model="banner" label-width="80px">
        <el-form-item label="海报">
          <el-image
            :lazy="true"
            :z-index="2555"
            v-if="banner.banner_url"
            :src="banner.banner_url"
            fit="cover"
            style="width: 250px"
            :preview-src-list="[banner.banner_url]"
          ></el-image>
          <el-upload
            :disabled="!is_set"
            class="upload-demo"
            :action="`${$http.defaults.baseURL}/upload_banner`"
            :on-success="afterUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="是否推荐"
          v-if="$store.getters.userInfo.grade === 'admin'"
        >
          <el-checkbox v-model="banner.is_recommend" :disabled="!is_set"
            >推荐</el-checkbox
          >
        </el-form-item>
        <el-form-item
          label="推荐时间"
          v-if="$store.getters.userInfo.grade === 'admin'"
        >
          <!-- 设置value-format v-model值显示格式也是按这个 -->
          <el-date-picker
            v-model="banner.recommend_at"
            :disabled="!is_set"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer" v-if="is_set">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitBanner">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  filters: {
    simpleIntro(intros) {
      return intros.length > 50 ? intros.substring(0, 51) + "..." : intros;
    },
  },

  data() {
    return {
      // 模拟弹框
      dialogVisible: false,
      list: null, //表格list [].push({})
      total: null,
      keyword: "",
      listQuery: {
        currPage: 1,
        pageSize: 10,
      },
      novels: [],
      typeOptions: [
        { key: "001", display_name: "类型1" },
        { key: "002", display_name: "类型2" },
        { key: "003", display_name: "类型3" },
      ],
      dialogFormVisible: false,
      multipleSelection: [],
      banner: {
        title: "作品名称",
        table_title: "cwm_novel",
        banner_url: "",
        is_recommend: "",
        recommend_at: "",
        work_id: "",
      },
      copyBanner: {},
      is_set: false, //判断是否是设置海报还是查看海报
    };
  },
  mounted() {
    this.copyBanner = JSON.parse(JSON.stringify(this.banner));
    this.getList();
  },
  methods: {
    afterUpload(res) {
      this.$set(this.banner, "banner_url", res.url);
    },
    closeBanner() {
      this.dialogVisible = false;
      this.banner = this.copyBanner;
    },
    // 展示banner
    async handleShow(row) {
      console.log(row);
      this.is_set = false;
      this.banner.work_id = row.novel_id;
      let res = await this.$http.get("/get_banner", { params: this.banner });
      this.banner = res.data || this.banner;
      this.dialogVisible = true;
    },
    // 展示banner，和设置banner
    async handleSet(row) {
      this.is_set = true;
      this.banner.work_id = row.novel_id;
      let res = await this.$http.get("/get_banner", { params: this.banner });
      this.banner = res.data || this.banner;
      console.log(res.data);
      this.dialogVisible = true;
    },
    // 上传banner的确认键
    async commitBanner() {
      let res = await this.$http.put("/update_banner", this.banner);
      this.$message({
        type: res.data.type,
        message: res.data.message,
      });
      console.log(this.banner);
       this.dialogVisible = false;
       this.banner = this.copyBanner;
    },
    //获取列表数据
    async getList() {
      let res = await this.$http.get("/novels", {
        params: {
          user_id: this.$store.getters.userInfo.user_id,
          pageSize: this.listQuery.pageSize,
          currPage: this.listQuery.currPage,
        },
      });
      this.novels = res.data.novels;
      this.listQuery.currPage = parseInt(res.data.currPage);
      this.listQuery.pageSize = parseInt(res.data.pageSize);
      this.total = res.data.total;
      console.log(res.data);
    },
    //编辑
    handleEdit(index, row) {
      this.$store.commit("SET_NOVEL", row);
      console.log("编辑的row：", index, "-----", row);
      this.$router.push("/novelsManage/novelUpdate");
    },

    //单个删除
    handleDelete(index, row) {
      let vm = this;
      console.log("单个删除选择的row：", index, "-----", row);

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          vm.delFun(row);
          //前端删除。
          vm.novels.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //调取删除接口的删除方法
    async delFun(row) {
      let novel_id = row.novel_id;
      let res = await this.$http.delete("/delete_novel", {
        params: { novel_id },
      });
      this.$message({
        type: res.data.type,
        message: res.data.message,
      });
    },
    //批量删除
    handleDelAll() {
      let vm = this;
      console.log("批量删除选择的row：", vm.multipleSelection);

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定批量删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //前端依次执行单个删除操作
          vm.novels = vm.novels.filter((item) => {
            for (let selection of vm.multipleSelection) {
              if (item.novel_id === selection.novel_id) {
                return false;
              }
            }
            return true;
          });
          for (var index in vm.multipleSelection) {
            console.log("======", vm.multipleSelection[index]);
            vm.delFun(vm.multipleSelection[index]);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //搜索
    async handleFilter() {
      let user_id = this.$store.getters.userInfo.user_id;
      let res = await this.$http.get("/search_novel", {
        params: {
          user_id,
          keyword: this.keyword,
          pageSize: this.listQuery.pageSize,
          currPage: this.listQuery.currPage,
        },
      });
      this.novels = res.data.novels;
      this.listQuery.currPage = parseInt(res.data.currPage);
      this.listQuery.pageSize = parseInt(res.data.pageSize);
      this.total = res.data.total;
      console.log(res.data);
    },
    //操作分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    //操作分页
    handleCurrentChange(val) {
      console.log("--------", val);
      this.listQuery.currPage = val;
      this.getList();
    },
    //新增
    handleCreate() {
      //跳到新增页面
      this.$router.push("/novelsManage/novelAdd");
    },
    //新增提交
    handleCreateSubmit() {
      let vm = this;
      console.log("新增入参：", vm.temp);

      //这里作演示用，正式新增 请提交到接口
      vm.list.push(vm.temp);
      console.log("新增后", vm.list);

      this.dialogFormVisible = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleDownload() {
      let vm = this;

      require.ensure([], () => {
        const { export_json_to_excel } = require("vendor/Export2Excel");
        const tHeader = [
          "小说名",
          "作者",
          "类型ID",
          "小说标签",
          "小说介绍",
          "小说状态",
          "小说封面",
        ];
        const filterVal = [
          "novel_title",
          "novel_author",
          "type_id",
          "novel_tag",
          "novel_intro",
          "novel_state",
          "cover",
        ];
        const list = vm.novels;
        const data = vm.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "小说表");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>
<style >
td {
  height: 100%;
}
</style>
